//
//  discoverController.m
//  Focus
//
//  Created by dlios on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "discoverController.h"
#import "discoverAddController.h"
#import "UIImageView+WebCache.h"
#import "discoverCell.h"
#import "SectionViewController.h"
#import "huancunCell.h"
#import "loginCell.h"
#import "cancelCell.h"
#import "friendCell.h"
#import <ShareSDK/ShareSDK.h>
#import "UIImageView+WebCache.h"
#import "Friend.h"
#import "myFriendController.h"
#import "focusUS.h"
//获取好友列表需要引进的头文件
#import <SinaWeiboConnection/SSSinaWeiboUser.h>
@interface discoverController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UISearchBar *searchBar;
@property (nonatomic, retain)UISearchDisplayController *disPlayController;
@property (nonatomic, retain)NSArray *array;
@property (nonatomic, retain) CDRTranslucentSideBar *sideBar;
@property(nonatomic,retain)UITableView *tableView1;
@property(nonatomic,retain)UILabel *nameLabel;
@property(nonatomic,retain)UIImageView *myImageView;
@property(nonatomic,retain)UIButton *loginButton;
@property(nonatomic,retain)NSMutableArray *friendArray;





@end


@implementation discoverController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.array = [NSArray array];
        self.friendArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.translucent = NO;
    //背景
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0];
#pragma mark -
#pragma mark - 导航栏标题设置
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
    title.text = @"发现";
    title.textColor = [UIColor whiteColor];
    title.font = [UIFont systemFontOfSize:18];
    title.textAlignment =  NSTextAlignmentCenter;
    title.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = title;
    [title release];
    //注销登陆
    //    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"注销"
    //        style:UIBarButtonItemStyleBordered
    //        target:self
    //        action:@selector(logoutButtonClickHandler:)]
    //        autorelease];
#pragma mark -
#pragma mark - 创建导航栏右边button
    //checkPlist
    [self checkPlist];
    
    //加载本地plist数据
    [self reloadPlist];
    
    //页面布局
    [self setupViews];
#pragma mark -
#pragma mark - 创建抽屉
    //  导航栏左侧推出列表抽屉
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-liebiao.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(leftBarAction:)];
    self.sideBar = [[CDRTranslucentSideBar alloc] init];
    self.sideBar.sideBarWidth = 200;
    self.sideBar.delegate = self;
    
    self.tableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 200, 568 - 64) style:UITableViewStylePlain];
    _tableView1.backgroundColor = [UIColor clearColor];
    _tableView1.dataSource = self;
    _tableView1.delegate = self;
    [self.sideBar setContentViewInSideBar:_tableView1];
#pragma mark -
#pragma mark - 注册cell
    [_tableView1 registerClass:[huancunCell class] forCellReuseIdentifier:@"huancun"];
    [_tableView1 registerClass:[loginCell class] forCellReuseIdentifier:@"login"];
    [_tableView1 registerClass:[cancelCell class] forCellReuseIdentifier:@"cancel"];
    [_tableView1 registerClass:[friendCell class] forCellReuseIdentifier:@"friend"];
    [_sideBar release];  
}

- (void)reloadPlist
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"apiBlockSorts.plist"];
    NSDictionary *readDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    self.array = [readDic objectForKey:@"_root"];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)setupViews
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    //    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(barButtonItemAction:)] autorelease];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
}

- (void)checkPlist
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"apiBlockSorts.plist"];
    NSDictionary *readDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    if (readDic == nil) {
        NSString *str = [[NSBundle mainBundle] pathForResource:@"apiBlockSorts" ofType:@"plist"];
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:str];
        
        BOOL result = [dic writeToFile:filePath atomically:YES];
        if (result) {
            NSLog(@"apiBlockSorts.plist归档成功");
        } else {
            NSLog(@"apiBlockSorts.plist归档失败");
        }
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];
    
    [noti postNotificationName:@"weatherChange1" object:self.array];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar removeFromSuperview];
}

- (void)dealloc
{
    [_nameLabel release];
    [_myImageView release];
    [_searchBar release];
    [_tableView release];
    [super dealloc];
}

#pragma mark --- tableView协议方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        return self.view.frame.size.height / 8;
    }else if (tableView == self.tableView1 && indexPath.section == 0 && indexPath.row == 0){
        return 80;
    }else if (tableView == self.tableView1 && indexPath.section == 1 &&indexPath.row == 0){
        return 55;
    }else if (tableView == self.tableView1 && indexPath.section == 2 &&indexPath.row == 0){
        return 55;
    }else if (tableView == self.tableView1 && indexPath.section == 3 &&indexPath.row == 0){
        return 55;
    }else if (tableView == self.tableView1 && indexPath.section == 4 &&indexPath.row == 0){
        return 55;
    }
    return 0;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return [self.array count];
    }else if(tableView == self.tableView1 && section == 0){
        return 1;
    }else if (tableView == self.tableView1 && section == 1){
        return 1;
    }else if (tableView == self.tableView1 && section == 2){
        return 1;
    }else if (tableView == self.tableView1 && section == 3){
        return 1;
    }else if (tableView == self.tableView1 && section == 4){
        return 1;
    }
    return 0;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.tableView) {
        return 1;
    }else if (tableView == self.tableView1){
        return 5;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        discoverCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nrk"];
        if (cell == nil) {
            cell = [[[discoverCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"nrk"]autorelease];
        }
        cell.titleLable.text = [self.array[indexPath.row] objectForKey:@"block_title"];
        NSString *imageStr = [self.array[indexPath.row] objectForKey:@"list_icon"];
        [cell.titleImageView sd_setImageWithURL:[NSURL URLWithString:imageStr]];
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        return cell;
        
    }else if (tableView == self.tableView1 && indexPath.section == 0 && indexPath.row == 0){
        loginCell *login = [tableView dequeueReusableCellWithIdentifier:@"login"];
        [login.myImageView setImage:[UIImage imageNamed:@"iconfont-yonghudenglu.png"]];
        login.login.text = @"新浪登陆";
        

       
        
        return login;
    }else if (tableView == self.tableView1 && indexPath.section == 1 &&indexPath.row == 0){
        huancunCell *huancun = [tableView dequeueReusableCellWithIdentifier:@"huancun"];
        huancun.label.text = @"清除缓存";
        [huancun.button setImage:[UIImage imageNamed:@"iconfont-qingchuhuancun.png"] forState:UIControlStateNormal];
        return huancun;
    }else if (tableView == self.tableView1 &&indexPath.section == 2 && indexPath.row == 0){
        cancelCell *cancel = [tableView dequeueReusableCellWithIdentifier:@"cancel"];
        cancel.cancel.text = @"注销登陆";
        //        [cancel.myImage setImage:[UIImage imageNamed:@"iconfont-zhuxiao.png"]];
        [cancel.button setImage:[UIImage imageNamed:@"iconfont-zhuxiao.png"] forState:UIControlStateNormal];
        return cancel;
    }else if (tableView == self.tableView1 && indexPath.section == 3 &&indexPath.row == 0){
        friendCell *friend = [tableView dequeueReusableCellWithIdentifier:@"friend"];
        friend.label.text = @"好友列表";
        [friend.button setImage:[UIImage imageNamed:@"iconfont-pengyouquan.png"] forState:UIControlStateNormal];
        return friend;
    }else if (tableView == self.tableView1 && indexPath.section == 4 ){
        friendCell *friend = [tableView dequeueReusableCellWithIdentifier:@"friend"];
        friend.label.text = @"关于我们";
        [friend.button setImage:[UIImage imageNamed:@"iconfont-jiaruwomen.png"] forState:UIControlStateNormal];
        return friend;

    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        if ([[self.array[indexPath.row] objectForKey:@"pk"] isEqualToString:@"44"] || [[self.array[indexPath.row] objectForKey:@"pk"] isEqualToString:@"68"] || [[self.array[indexPath.row] objectForKey:@"pk"] isEqualToString:@"121"]) {
            
            SectionViewController *sectionVC = [[SectionViewController alloc]init];
            
            sectionVC.api_url = [self.array[indexPath.row] objectForKey:@"api_url"];
            
            sectionVC.numberSons = indexPath.row;
            
            [self.navigationController pushViewController:sectionVC animated:YES];
            
            
        } else {
            
            
            
            discoverAddController *discoverAdd = [[discoverAddController alloc] init];
            discoverAdd.numberSons = indexPath.row;
            discoverAdd.receiveTitle = [self.array[indexPath.row] objectForKey:@"block_title"];
            [self.navigationController pushViewController:discoverAdd animated:YES];
        
        }
        
    }else if (tableView == self.tableView1 &&indexPath.section == 0 && indexPath.row == 0){
        [ShareSDK getUserInfoWithType:ShareTypeSinaWeibo authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
            if (result) {
                NSLog(@"新浪微博授权成功！");
                NSLog(@"uid:%@",[userInfo uid]);
                NSLog(@"nickname:%@",[userInfo nickname]);
                NSLog(@"profileImage:%@",[userInfo profileImage]);
 
                NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
                [center postNotificationName:@"cesuo" object:[userInfo profileImage] userInfo:nil];
                NSNotificationCenter *center1 = [NSNotificationCenter defaultCenter];
                [center1 postNotificationName:@"cesuo1" object:[userInfo nickname] userInfo:nil];
                
                UIAlertView* alverView = [[UIAlertView alloc]initWithTitle:nil message:@"授权成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alverView show];
                //创建一个key为signin的数据库记录授权成功状态
                [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"signin"];
                                
                }else{
                } else{
                NSLog(@"新浪微博授权失败");
                NSLog(@"错误码:%d,错误描述:%@",[error errorCode],[error errorDescription]);
                
            }
        }];
        
        
    }else if (tableView == self.tableView1 && indexPath.section == 1 &&indexPath.row == 0){
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *path = [paths lastObject];
        
        
        NSString *str = [NSString stringWithFormat:@"当前缓存%.1fM", [self folderSizeAtPath:path]];
        
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
        for (NSString *p in files) {
            NSError *error;
            NSString *Path = [path stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
                [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
            }
        }
        
        //提示框
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定清除缓存" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
        [alert release];
        
        
    }else if (tableView == self.tableView1 &&indexPath.section == 2 && indexPath.row == 0){
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"signin"] == nil) {
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"未登录,请登录" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            [alert show];
            [alert release];
        }else {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"确定注销新浪微博" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert1 show];
        [alert1 release];
        [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];
            NSNotificationCenter *center2 = [NSNotificationCenter defaultCenter];
            [center2 postNotificationName:@"cesuo2" object:[UIImage imageNamed:@"iconfont-yonghudenglu.png"] userInfo:nil];
            
            NSNotificationCenter *center3 = [NSNotificationCenter defaultCenter];
            [center3 postNotificationName:@"cesuo3" object:@"新浪登陆" userInfo:nil];
            //未成功的标志位nil
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"signin"];
         }
                   
    }
     else if (tableView == self.tableView1 &&indexPath.section == 3 && indexPath.row == 0){
    } else if (tableView == self.tableView1 &&indexPath.section == 3 && indexPath.row == 0){
        [ShareSDK getFriendsWithType:ShareTypeSinaWeibo page: nil authOptions:nil result:^(SSResponseState state, NSArray *users, long long curr, long long prev, long long next, BOOL hasNext, NSDictionary *extInfo, id<ICMErrorInfo> error) {
            if (state == SSResponseStateSuccess) {
                
                
                for (SSSinaWeiboUser *user in users) {
                    Friend *friend = [[Friend alloc]init];
                    
                    friend.idNum = user.uid;
                    friend.name = user.nickname;
                    friend.profileImage = user.profileImage;
                    //                    NSLog(@"**********%@", friend.idNum);
                    //                    NSLog(@"%@", friend.name);
                    [self.friendArray addObject:friend];
                    [friend release];
                    
                    
                }
            }
            myFriendController *myFriend = [[myFriendController alloc]init];
            myFriend.array = self.friendArray;
            [self presentViewController:myFriend animated:YES completion:^{
                
            }];
            
        }];
        
    } else if (tableView == self.tableView1 &&indexPath.section == 4 && indexPath.row == 0){
        focusUS *focus = [[focusUS alloc]init];
        [self presentViewController:focus animated:YES completion:^{
            
        }];

//        [self.navigationController pushViewController:focus animated:YES];

    }
}


#pragma mark -
#pragma mark -设置section高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView1) {
        if (section == 0) {
            return 20;
        }else if (section == 1){
            return 20;
        }else if (section == 2){
            return 20;
        }else if (section == 3){
            return 20;
        }else if (section == 4){
            return 20;
        }
    }
    
    return 0;
    
}
#pragma mark -
#pragma mark -清除缓存
//文件大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历所有文件
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
//Alert点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIButton *button = (UIButton *)[self.view viewWithTag:5000];
    [button setTitle:@"清除缓存" forState:UIControlStateNormal];
}

#pragma mark -
#pragma mark -抽屉实现的点击事件方法
//  导航栏左侧按钮实现的方法
- (void)leftBarAction:(UIBarButtonItem *)button
{
    [self.sideBar show];
}
//注销点击事件
- (void)logoutButtonClickHandler:(id)sender
{
    UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"确定注销新浪微博" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert1 show];
    [alert1 release];
    [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];
    
    [self.navigationController popViewControllerAnimated:NO];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end